package top.andnux.weather.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import top.andnux.weather.model.MainModel;

public class WeatherService extends Service {

    public static final String ACTION = "top.andnux.weather";

    /**
     * 启动天气服务进行更新数据
     *
     * @param context
     * @param city
     */
    public static void start(Context context, String city) {
        Intent intent = new Intent(context, WeatherService.class);
        intent.putExtra("city", city);
        context.startService(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @SuppressLint("StaticFieldLeak")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String city = intent.getStringExtra("city");
        new AsyncTask<String, Void, String>() {
            @Override
            protected String doInBackground(String... strings) {
                StringBuilder response;
                try {
                    String apiUrl = "http://apis.juhe.cn/simpleWeather/query";
                    HashMap<String, String> map = new HashMap<>();
                    map.put("key", "515a64ce1d92c586076ef2ed55bab33e");
                    map.put("city", city);
                    URL url = new URL(String.format("%s?%s", apiUrl, params(map)));
                    BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
                    String inputLine;
                    response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    return response.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "";
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                MainModel mainModel = new Gson().fromJson(s, MainModel.class);
                Intent intent1 = new Intent(ACTION);
                intent1.putExtra("data", mainModel);
                sendBroadcast(intent1);
            }
        }.execute();


        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 拼接参数
     *
     * @param map
     * @return
     */
    private String params(Map<String, String> map) {
        return map.entrySet().stream().map(entry -> {
            try {
                return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return entry.getKey() + "=" + entry.getValue();
            }
        }).collect(Collectors.joining("&"));
    }
}